package com.sb.hot.ext.convert;

import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.converter.Converter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class MyConversionServiceFactoryBean {
    @Bean
    public ConversionServiceFactoryBean conversionService() {
        ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean(); Set<Converter> set = new HashSet<>(); set.add(new UserToStringConvert());
        set.add(new StrToListConvert()); conversionServiceFactoryBean.setConverters(set); return conversionServiceFactoryBean;
    }

    static class StrToListConvert implements Converter<String, List<User>> {
        @Override
        public List<User> convert(String source) {
            try {
                String name = User.class.getName(); Class<User> aClass = (Class<User>) Thread.currentThread().getContextClassLoader().getParent().loadClass(name);
                List<User> users = JSON.parseArray(source).toJavaList(aClass); return users;
            } catch (Throwable e) {
                // e.printStackTrace();
            } return null;
            // Thread.currentThread().getContextClassLoader().getParent().loadClass(User.class.getName())
            // return JSON.parseArray(source).toJavaList(User.class);
        }
    }
}
